<template>
	<div class="page">
		<div class="answer">
			<div class="answerMain">
				<div class="answerMain-bd">
					<div class="answerMain-item">
						<div class="answerMain-item__content" style="padding: 0px 0px; overflow-y: :scroll;">
							<span class="defaultQuestion-title">您好，我是智能助手！</span>
							作为您的智能助手，我能帮助您解决各种问题。
							除此之外，小助还可以尝试帮助解决其他方面的问题或在您需要的时候陪您聊天！
							您可以试着问我：
							<div class="defaultQuestion">
								<div class="defaultQuestion-item" @click="onClickDefaultQuestion($event, item)"
									v-for="item in defaultQuestion.list" :key="item.id" :span="12">
									{{ item.value }}
								</div>
							</div>
						</div>
					</div>
					<div v-for="item in answerList" :class="['answerMain-item', {'roleUser': item.role === 'user' }]">
						<img v-show="item.role === 'assistant'" src="@/static/ai-avatar.png"
							class="answerMain-item__avatar" />
						<img v-show="item.role === 'user'" src="@/static/ai-question-avatar.png"
							class="answerMain-item__avatar" />
						<div class="">
							<div v-if="item.role === 'user'" class="answerMain-item__content">{{ item.content }}</div>
							<div v-else-if="item.role === 'assistant'" class="answerMain-item__content">
								<div class="answerMain-item__outputReasonContent">{{ item.reasoning_content }}</div>
								<zero-markdown-view :markdown="item.content" themeColor="#05073b"></zero-markdown-view>
								
								<!-- AI分析部分 -->
								<div  class="ai-section">
									<div class="section-header">
										<div class="section-icon">🔍</div>
										<div class="section-title">AI问题分析</div>
									</div>
									<div class="ai-content">
										诊断思路：我们将采取以下步骤来诊断并解决这个问题：
									</div>
									<div class="emergency-badge">紧急程度：中</div>
									<div class="ai-content">计划步骤：4步</div>
								</div>
								<!-- 步骤部分 -->
								<div class="step-section">
									<div class="step-item">
										<div class="step-header">
											<div class="step-number">1</div>
											<div class="step-title">第 1/4 步：Ping测试  </div>
										</div>
									</div>
								</div>
											
							  <div class="test-card">
								<div class="test-header">
								  <div class="test-icon">1️⃣</div>
								  <div class="test-title">Ping测试</div>
								  <div class="priority-badge">高优先级</div>
								  <div class="time-estimate">5-10秒</div>
								</div>
							   </div>

							<div class="reason-box">
							  <strong>推荐理由：</strong>使用ping命令检查网络连通性和延迟，确定是否存在基本的网络连接问题
							</div>
					  
							        <div class="params-section">
							          <div class="params-toggle">
							            <span>参数配置 (2)<a>【下一步】</a> </span>
							            <span>▼</span>
							          </div>
							        </div>
							        <button class="execute-btn">立即执行</button>
							</div>
							
						</div>
					</div>



				</div>





				<div class="answerMain-ft">
					<div class="answerMain-input">
						<textarea v-model.trim="answerKeyword" @keydown.enter.native="onSubmit" placeholder="请输入问题"
							class="answerMain-input__textarea"></textarea>
						<div style="display: flex; justify-content: flex-end;">
							<button @click="onSubmit" :loading="submitLoading" type="primary"
								class="answerMain-input__button">
								发送
							</button>
						</div>
					</div>
				</div>



			</div>
		</div>
	</div>
</template>

<style scoped>

</style>


<script>
	import {
		ref
	} from 'vue';
	import {
		GetAPI
	} from '../../api/system/ai/aiAPI.js'



	export default {
		components: {},
		data() {
			return {
				buffer: '', // 用于存储流式数据不完整的行
				defaultQuestion: {
					list: [{
						id: 2,
						value: '我家宽带无法上网',
					}, ]
				},
				submitLoading: false,
				answerKeyword: '',
				answerList: [],
				// 会话记录
				chatHistory: {
					list: [],
					questionId: undefined,
				}
			}
		},
		created() {
			this.getChatList()
		},

		methods: {
			exe_ping() {
				alert('执行ping')
			},
			onClickCreateChat() {
				if (this.chatHistory.list.length >= 10) {
					return uni.showToast({
						title: '您最多可同时建立10个对话，如需新建对话，请先删除会话！',
						icon: 'none'
					})
				}
				this.chatHistory.questionId = undefined
				this.answerList = []
				this.answerKeyword = ''
			},
			onClickEditTitle(item) {
				this.chatHistory.list.map(item => item._edit = false)
				item._edit = true
				this.$nextTick(() => {

				})
			},

			saveChatTitle(item) {
				uni.showToast({
					title: '触发修改',
					icon: 'none'
				})
				this.getChatList()
			},
			confirmDeletion(item) {
				uni.showModal({
					title: '提示',
					content: '确定删除吗'
				})
			},
			onClickDefaultQuestion(event, item) {
				this.answerKeyword = item.value
				this.onSubmit(event)
			},

			getChatList() {
				setTimeout(() => {
					this.chatHistory.list = [{
						"id": 31,
						"title": "统计学专业就业好不好？",
						"createDate": "2024-07-31 15:13:49",
						"updateDate": null,
						"itemList": [{
								"id": 136,
								"questionId": 30,
								"role": "user",
								"content": "统计学专业就业好不好？",
								"createDate": "2024-07-31 15:13:49",
								"updateDate": null
							},
							{
								"id": 137,
								"questionId": 30,
								"role": "assistant",
								"content": "#### 统计学专业的就业前景相对较好，具有广阔的发展空间。",
								"reasoning_content": "统计学专业的就业前景相对较好，具有广阔的发展空间。",
								"createDate": "2024-07-31 15:13:49",
								"updateDate": null
							}
						]
					}]
				}, 1000);
				this.chatHistory.list.map(item => {
					item._edit = false
					item._editTitle = item.title
					return item
				})
			},

			onClickChatItem(item) {
				this.chatHistory.questionId = item.id
				this.answerList = item.itemList

				this.$nextTick(() => {
					let elem = document.querySelector('.answerMain-bd')
					elem.scrollTop = elem.scrollHeight
				})
			},


			async onSubmit(event) {
				var that = this;
				debugger;
				console.log('event', event);
				if (event.keyCode === 13 || event.key === "Enter") {
					event.preventDefault(); // 阻止默认行为，即回车换行
					if (event.shiftKey) {
						this.answerKeyword += "\n";
					}
				}



				if (!this.answerKeyword) {
					return uni.showToast({
						title: '请输入内容',
						icon: 'none'
					})
				}
				if (this.submitLoading) return
				this.submitLoading = true
				this.answerList.push({
					role: 'user',
					content: this.answerKeyword,
				})
				//that.$vm.answerKeyword = '';

				/* 本地测试  */
	  this.answerList.push({
	    role: 'assistant',
	    content: '',
	    reasoning_content: that.answerKeyword,
	  })
	  //that.done = true;
	  that.submitLoading = false
	  that.$nextTick(() => {
		let elem = document.querySelector('.answerMain-bd')
		elem.scrollTop = elem.scrollHeight
		// window.scrollTo(0, document.body.scrollHeight)
	  })
	 

				that.$nextTick(() => {
					let elem = document.querySelector('.answerMain-bd')
					elem.scrollTop = elem.scrollHeight
				});

				// that.answerList.push({
				// 	role: 'assistant',
				// 	content: '',
				// 	reasoning_content: '思考中...',
				// });

				// var response = GetAPI('asdasd')
				// response.then(function(data) {
				// 	that.answerList.pop()

				// 	that.answerList.push({
				// 		role: 'assistant',
				// 		content: '',
				// 		reasoning_content: data, //data
				// 	});
				// 	that.$nextTick(() => {
				// 		let elem = document.querySelector('.answerMain-bd')
				// 		elem.scrollTop = elem.scrollHeight
				// 	})
				// 	that.submitLoading = false
				// 	that.answerKeyword = '';
				// })




			},
			processSSEChunk(chunk) {
				// 按行拆分数据块
				this.buffer += chunk
				const lines = this.buffer.split('data:')
				// 检查最后一行是否完整
				if (!chunk.endsWith('\n')) {
					// 如果最后一行不完整，保留在缓冲区中
					this.buffer = lines.pop();
				} else {
					// 如果最后一行完整，清空缓冲区
					this.buffer = '';
				}
				lines.forEach((line, index) => {
					// 检查是否是SSE格式的数据行
					// 提取JSON部分
					const jsonString = line;
					// 如果JSON部分不为空，则解析
					if (jsonString === '[DONE]') {
						this.answerList[this.answerList.length - 1].content += ''
					} else if (jsonString !== '') {
						try {
							const jsonData = JSON.parse(jsonString);
							if (jsonData.questionId && !this.chatHistory.questionId) {
								this.getChatList()
								this.chatHistory.questionId = jsonData.questionId
							}
							if (jsonData.reasoning_content) {
								this.answerList[this.answerList.length - 1].reasoning_content += jsonData
									.reasoning_content
							} else if (jsonData.content) {
								this.answerList[this.answerList.length - 1].content += jsonData.content
							}
						} catch (error) {
							console.log('parsing JSON错误', jsonString, index);
							console.log('parsing JSON错误', error);
						}
					}
					this.$nextTick(() => {
						let elem = document.querySelector('.answerMain-bd')
						elem.scrollTop = elem.scrollHeight
						// window.scrollTo(0, document.body.scrollHeight)
					})
				});
			},
		},
	}
</script>

<style lang="scss" scoped>
	uni-page-body,
	html,
	body {
		height: 100%;
	}

	.page {
		background: #f9f9f9;
		height: 100%;
	}

	.modify-icon {
		display: inline-block;
		font-size: 14px;
		padding: 5px;
		cursor: pointer;

		&:hover {
			background: #e1e5fa;
			border-radius: 4px;
			color: PrimaryColor;
		}
	}

	.createChat-button {
		font-size: 14px;
	}

	.defaultQuestion-title {
		color: #05073b;
		font-size: 26px;
		font-weight: 600;
		line-height: 36px;
		margin-bottom: 8px;
	}

	.defaultQuestion {
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		column-gap: 10px;
	}

	.defaultQuestion-item {
		padding: 16px;
		background: #f6f8fd;
		border-radius: 6px;
		margin-top: 10px;
		cursor: pointer;
		font-size: 16px;
		font-weight: 600;

		.modify-icon {
			font-size: 16px;

			&:hover {
				background: unset;
			}
		}

		&:hover {
			background: #e9ecfb;
			color: PrimaryColor;
		}
	}

	.answer {
		display: flex;
		justify-content: center;
		height: 100%;
		padding: 10px;
		box-sizing: border-box;
	}

	.answerLeft {
		width: 280px;
		margin-right: 10px;
		background: linear-gradient(180deg, #f5f4f6, #e6ebf7);
		border-radius: 8px;
		padding: 15px 10px 0 10px;
	}

	.answerLeft-deleteConfirm {
		padding: 12px 0;
		text-align: center;
	}

	.answerLeft-deleteConfirm__btn {
		width: 92px;
		height: 32px;
		line-height: 32px;
		padding: 0 4px;
	}

	.modify-title {
		border: 1px solid #dcdfe6;
		height: 32px;
		line-height: 32px;
		border-radius: 8px;
		width: 100%;
		padding: 0 12px;
	}

	.answerMain {
		padding-top: 9px;
		font-size: 15px;
		display: flex;
		flex-direction: column;
		background: linear-gradient(180deg, #f5f4f6, #e6ebf7);
		width: 900px;
		border-radius: 8px;
	}

	.answerMain-bd {
		flex-grow: 1;
		height: 0;
		overflow-y: auto;
		flex-direction: column;
		display: flex;
		background: unset;
		box-sizing: border-box;

		&::-webkit-scrollbar-thumb {
			border-radius: 4px;
			background: rgba(108, 119, 143, 0.3);
		}

		&::-webkit-scrollbar {
			height: 20px;
			width: 4px;
		}
	}

	.answerMain-ft {
		flex-shrink: 0;
		min-height: 50px;
		padding: 6px 6px 6px 6px;
		box-sizing: border-box;
	}

	.chatHistory-item {
		display: flex;
		align-items: center;
		padding: 0 10px 0 0;
		margin-top: 10px;

		&:hover {
			.chatHistory-item__handle {
				display: block;
			}
		}
	}

	.chatHistory-item:hover,
	.chatHistory-item.is-active {
		background: rgba(255, 255, 255, 0.9);
		border-radius: 8px;
		box-shadow: 0 16px 20px 0 rgba(173, 167, 224, 0.06);
		color: initial;
	}

	.chatHistory-item__hd {
		flex-shrink: 0;
	}

	.chatHistory-item__bd {
		flex: 1;
		color: #000c3f;
		cursor: pointer;
		display: flex;
		align-items: center;
		font-size: 14px;
		font-weight: 400;
		height: 50px;
		line-height: 50px;
		overflow: hidden;
		padding: 0 10px 0 10px;
		position: relative;
		text-align: justify;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.chatHistory-item__handle {
		flex-shrink: 0;
		display: none;
	}

	.answerMain-item {
		padding: 40px 10px;
		color: #05073b;
		position: relative;
		display: flex;

		&.roleUser {
			justify-content: end;

			.answerMain-item__avatar {
				left: unset;
				right: 40px;
			}
		}
	}

	.answerMain-item__avatar {
		width: 26px;
		height: 26px;
		border-radius: 50%;
		position: absolute;
		top: 12px;
		left: 40px;
	}

	.answerMain-item__content {
		background: #fdfdfe;
		border-radius: 8px;
		box-shadow: 0 16px 20px 0 rgba(174, 167, 223, 0.06);
		display: flex;
		flex-direction: column;
		padding: 12px 20px;
		position: relative;
		font-size: 15px;
		line-height: 1.75;
		min-height: 50px;
		box-sizing: border-box;
	}

	.answerMain-item__outputReasonContent {
		color: #666;
		border-left: 3px solid #ddd;
		padding-left: 13px;
		margin: 5px 0;
		line-height: 1.5;
	}

	.answerMain-input {
		background: #fff;
		padding: 12px 16px;
		border-radius: 10px;
		box-shadow: 0 16px 20px 0 rgba(174, 167, 223, 0.2);
		min-height: 50px;
	}

	.answerMain-input__textarea {
		height: 50px;
		width: 100%;

		::v-deep {
			.el-textarea__inner {
				border: none;
				resize: none;
				color: #05073b;
			}
		}
	}

	.answerMain-input__button {
		font-size: 12px;
		padding: 0 20px;
		align-self: end;
		margin: 0;
	}
</style>


<style lang="scss" scoped>
	* {
		margin: 0;
		padding: 0;
		box-sizing: border-box;
	}

	body {
		font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
		background-color: #f5f7fa;
		color: #333;
	}

	.chat-container {
		max-width: 800px;
		margin: 0 auto;
		background-color: #fff;
		min-height: 100vh;
	}

	.progress-bar {
		padding: 15px;
		background-color: #fff;
		border-bottom: 1px solid #eee;
	}

	.progress-text {
		font-size: 14px;
		margin-bottom: 8px;
		color: #666;
	}

	.dots {
		display: flex;
		gap: 6px;
	}

	.dot {
		width: 6px;
		height: 6px;
		border-radius: 50%;
		background-color: #ddd;
	}

	.dot.active {
		background-color: #409eff;
	}

	.message-area {
		padding: 20px;
	}

	.user-message {
		display: flex;
		justify-content: flex-end;
		margin-bottom: 20px;
	}

	.user-bubble {
		background-color: #409eff;
		color: white;
		padding: 10px 15px;
		border-radius: 10px 10px 0 10px;
		max-width: 70%;
		position: relative;
	}

	.user-avatar {
		width: 36px;
		height: 36px;
		border-radius: 50%;
		background-color: #ddd;
		margin-left: 10px;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 18px;
	}

	.ai-section {
		background-color: #f0f9ff;
		border-radius: 12px;
		padding: 15px;
		/*margin-bottom: 20px;*/
	}

	.section-header {
		display: flex;
		align-items: center;
		margin-bottom: 10px;
	}

	.section-icon {
		width: 24px;
		height: 24px;
		border-radius: 4px;
		background-color: #409eff;
		color: white;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 14px;
		margin-right: 8px;
	}

	.section-title {
		font-weight: bold;
		color: #409eff;
		font-size: 15px;
	}

	.ai-content {
		font-size: 14px;
		line-height: 1.6;
		color: #333;
		margin-top: 5px;
		/*margin-bottom: 10px;*/
	}

	.emergency-badge {
		display: inline-block;
		background-color: #f7ba2a;
		color: white;
		padding: 2px 8px;
		border-radius: 12px;
		font-size: 12px;
		margin-top: 8px;
	}

	.step-section {
		background-color: #ecf5ff;
		border-radius: 12px;
		margin-bottom:5px;
		margin-top:5px;
		/*padding: 15px;
	     margin-bottom: 20px;*/
	}

	.step-item {
		background-color: #e6f2ff;
		border-radius: 8px;
		/*padding: 12px;
		margin-bottom: 15px;*/
	}

	.step-header {
		display: flex;
		align-items: center;
		margin-bottom: 5px;
	}

	.step-number {
		background-color: #409eff;
		color: white;
		width: 20px;
		height: 20px;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 12px;
		margin-right: 8px;
	}

	.step-title {
		font-weight: bold;
		font-size: 14px;
	}

	.test-card {
		background-color: white;
		border-radius: 12px;
		padding-top: 10px;
		padding-left: 5px;
		margin-bottom: 5px;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
	}

	.test-header {
		display: flex;
		align-items: center;
		margin-bottom: 10px;
	}

	.test-icon {
		background-color: #409eff;
		color: white;
		width: 28px;
		height: 28px;
		border-radius: 8px;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 14px;
		margin-right: 10px;
	}

	.test-title {
		font-weight: bold;
		font-size: 15px;
		flex: 1;
	}

	.priority-badge {
		background-color: #f56c6c;
		color: white;
		padding: 2px 8px;
		border-radius: 12px;
		font-size: 12px;
	}

	.time-estimate {
		font-size: 12px;
		color: #999;
		margin-left: 8px;
	}

	.reason-box {
		background-color: #f5f7fa;
		border-radius: 8px;
		padding: 12px;
		margin-bottom: 5px;
		font-size: 13px;
		color: #666;
	}

	.params-section {
		margin-bottom: 15px;
	}

	.params-toggle {
		display: flex;
		justify-content: space-between;
		align-items: center;
		font-size: 14px;
		color: #666;
		padding: 8px 0;
		cursor: pointer;
	}

	.execute-btn {
		background-color: #409eff;
		color: white;
		border: none;
		border-radius: 8px;
		/*padding: 12px 20px;*/
		width: 100%;
		font-size: 16px;
		cursor: pointer;
	}

	.bottom-tabs {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: white;
		display: flex;
		justify-content: space-around;
		padding: 10px 0;
		box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
		z-index: 100;
	}

	.tab-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		color: #909399;
		font-size: 12px;
	}

	.tab-item.active {
		color: #409eff;
	}

	.tab-icon {
		font-size: 20px;
		margin-bottom: 4px;
	}

	.chat-input-area {
		padding: 20px;
		padding-bottom: 80px;
	}

	.input-box {
		background-color: #f5f7fa;
		border-radius: 20px;
		padding: 10px 15px;
		display: flex;
		align-items: center;
	}

	.message-input {
		flex: 1;
		border: none;
		background: none;
		outline: none;
		font-size: 14px;
	}

	.send-btn {
		background-color: #409eff;
		color: white;
		border: none;
		border-radius: 50%;
		width: 32px;
		height: 32px;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 16px;
		margin-left: 10px;
		cursor: pointer;
	}
</style>